-module(dispatcher_test).
-export([setup/0]).

-include("edrp_server.hrl").

setup() ->
    Addr1 = #addr{ip="127.0.0.1", port=80},   
    Addr2 = #addr{ip="127.0.0.1", port=8888},
    Server1 = #server{addr=Addr1, load=0, weight=?DEFAULT_WEIGHT},
    Server2 = #server{addr=Addr2, load=0, weight=?DEFAULT_WEIGHT},
    ServerList = [Server2, Server1],
    edrp_dispatcher:start(),
    test_add_delete(Addr1, Addr2, Server1, Server2, ServerList),
    test_apply_return(Addr1, Addr2),
    test_change_loadFunc(Addr1, Addr2).
    
test_add_delete(Addr1, Addr2, Server1, Server2, ServerList) ->
    true = edrp_dispatcher:list_server() == [],
    edrp_dispatcher:add_server(Addr1),
    edrp_dispatcher:add_server(Addr2),
    true = edrp_dispatcher:list_server() == ServerList,
    edrp_dispatcher:delete_server(Addr1),
    edrp_dispatcher:delete_server(Addr2),
    true = edrp_dispatcher:list_server() == [],
    edrp_dispatcher:add_serverList(lists:reverse(ServerList)),
    true = edrp_dispatcher:list_server() == ServerList,
    edrp_dispatcher:delete_all_servers(),
    true = edrp_dispatcher:list_server() == [],
    edrp_dispatcher:add_serverList(lists:reverse(ServerList)),
    edrp_dispatcher:add_server(Server1#server.addr, Server1#server.weight),
    edrp_dispatcher:add_server(Server2#server.addr, Server2#server.weight),
    true = edrp_dispatcher:list_server() == ServerList,
    ok.

test_apply_return(Addr1, Addr2) ->
    Addr2 = edrp_dispatcher:apply_server(""),
    Addr1 = edrp_dispatcher:apply_server(""),
    Addr2 = edrp_dispatcher:apply_server(""),
    edrp_dispatcher:return_server(Addr2, true),
    Addr2 = edrp_dispatcher:apply_server(""),
    edrp_dispatcher:return_server(Addr1, true),
    Addr1 = edrp_dispatcher:apply_server(""),
    ok.

test_change_loadFunc(Addr1, Addr2) ->
    "least load" = edrp_dispatcher:get_loadFunc(),
    NewLoadFunc = #loadFunc{func=fun(Loads) ->
                                    edrp_load:rrobin(Loads)
                                 end, 
                            name="round robin"},
    edrp_dispatcher:set_loadFunc(NewLoadFunc),
    "round robin" = edrp_dispatcher:get_loadFunc(), 
    Addr2 = edrp_dispatcher:apply_server(""),
    edrp_dispatcher:return_server(Addr1, true),
    Addr1 = edrp_dispatcher:apply_server(""),
    edrp_dispatcher:return_server(Addr1, true),
    Addr2 = edrp_dispatcher:apply_server(""),
    edrp_dispatcher:dump(),
    ok.
